package main.leetcode.offer.firstround.from03to50;

import main.datastruc.TreeNode;

import java.util.Deque;
import java.util.LinkedList;

/**
 * 28.对称的二叉树
 *
 * <p>请实现一个函数，用来判断一棵二叉树是不是对称的。如果一棵二叉树和它的镜像一样，那么它是对称的。
 *
 * <p>示例 1：输入：root = [1,2,2,3,4,4,3] 输出：true
 *
 * <p>示例 2：输入：root = [1,2,2,null,3,null,3] 输出：false
 *
 * <p>限制：0 <= 节点个数 <= 1000
 *
 * <p>来源：力扣（LeetCode） 链接：https://leetcode-cn.com/problems/dui-cheng-de-er-cha-shu-lcof
 * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
 */
public class ex28 {

    // 递归
    public boolean isSymmetric(TreeNode root) {
        if (root == null || root.left == null && root.right == null) return true;
        return isSymmetric(root.left, root.right);
    }

    private boolean isSymmetric(TreeNode left, TreeNode right) {
        if (left == null) return right == null;
        if (right == null) return false;
        return left.val == right.val
                && isSymmetric(left.left, right.right)
                && isSymmetric(left.right, right.left);
    }

    // 非递归
    public boolean isSymmetric1(TreeNode root) {
        if (root == null || root.left == null && root.right == null) return true;
        Deque<TreeNode> deque = new LinkedList<>();
        deque.addFirst(root.left);
        deque.addLast(root.right);
        TreeNode left, right;
        while (!deque.isEmpty()) {
            left = deque.pollFirst();
            right = deque.pollLast();
            if (left == null && right == null) continue;
            if (right == null || left == null) return false;
            if (left.val != right.val) return false;
            deque.addFirst(left.left);
            deque.addLast(right.right);
            deque.addFirst(left.right);
            deque.addLast(right.left);
        }
        return true;
    }
}
